/*
 * @author Nieves Grinan Garrido
 */
package formula_urjc;

import clases.Escuderia;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import static java.lang.Integer.parseInt;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Senpai
 */
public class ListaEscuForm extends javax.swing.JFrame {
 
    DefaultTableModel dtmEjemplo;
        public ListaEscuForm(){
            initComponents();
        //Llenamos el modelo
        dtmEjemplo = new DefaultTableModel(null,getColumnas());
 
        setFilas();
 
        this.tablaEscu.setModel(dtmEjemplo);
        this.setSize(500, 500);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
    }
  

    //Encabezados de la tabla
    private String[] getColumnas()
    {
          String columna[]=new String[]{"Nombre","Año Fundación","Presupuesto", "Puntos", "Pais"};
          return columna;
    }
 
    private void setFilas()
    {
       FileInputStream f = null;
       DataInputStream entrada = null;
       try {
           
           Escuderia escuAux;
           f = new FileInputStream("escuderia.dat");
           entrada = new DataInputStream(f);
           int n =0;
           //Para controlar si el registro existe
           while (n!=-1) { 
                escuAux = leerFichero(entrada);
                if((escuAux==null)||(escuAux.getNombre().equals(""))){
                    n = -1;
                }else{
                    String nombre = escuAux.getNombre();
                    Integer anio = escuAux.getAnyoFundacion();
                    Integer presupuesto = escuAux.getPresupuesto();
                    Integer puntos = escuAux.getPuntos();
                    String pais = escuAux.getPais();
                    Object objeto[]={nombre, anio, presupuesto, puntos, pais};
                    dtmEjemplo.addRow(objeto); 
                }
            }
        
           
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (EOFException e) {
            System.out.println("Fin de fichero");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
       
    }
    //Metodo que recoge el contenido del fichero
     private Escuderia leerFichero(DataInputStream raf) throws IOException {
                byte[] record = new byte[Escuderia.SIZE];
                raf.read(record);
                return Escuderia.fromBytes(record);
            }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        labelEscu = new java.awt.Label();
        altaB = new javax.swing.JButton();
        bajaB = new javax.swing.JButton();
        modificarB = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaEscu = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        labelEscu.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
        labelEscu.setText("Lista Escuderias");

        altaB.setText("Alta");
        altaB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                altaBActionPerformed(evt);
            }
        });

        bajaB.setText("Borrar");
        bajaB.setToolTipText("");
        bajaB.setEnabled(false);
        bajaB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bajaBActionPerformed(evt);
            }
        });

        modificarB.setText("Modificar");
        modificarB.setEnabled(false);
        modificarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarBActionPerformed(evt);
            }
        });

        tablaEscu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Nombre", "Año fundación", "Presupuesto", "Puntos", "Pais"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaEscu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                seleccionarItem(evt);
            }
        });
        jScrollPane1.setViewportView(tablaEscu);
        if (tablaEscu.getColumnModel().getColumnCount() > 0) {
            tablaEscu.getColumnModel().getColumn(4).setResizable(false);
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(altaB)
                        .addGap(18, 18, 18)
                        .addComponent(bajaB)
                        .addGap(18, 18, 18)
                        .addComponent(modificarB))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelEscu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 511, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(labelEscu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(altaB)
                    .addComponent(bajaB)
                    .addComponent(modificarB))
                .addGap(58, 58, 58))
        );

        labelEscu.getAccessibleContext().setAccessibleName("Lista de coches");
        labelEscu.getAccessibleContext().setAccessibleDescription("");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/formula_urjc/images/Pirelli_Formula-1_2013_4_1.jpg"))); // NOI18N
        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(389, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(106, 106, 106))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void altaBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_altaBActionPerformed
        AltaEscuderia alta = new AltaEscuderia();
        this.setVisible(false);
        alta.setVisible(true);
    }//GEN-LAST:event_altaBActionPerformed

    private void bajaBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bajaBActionPerformed
        BorrarEscuderia borrar = null;
        int row = this.tablaEscu.getSelectedRow();
        String nombre = String.valueOf(this.tablaEscu.getValueAt(row,0));
        Integer anio = parseInt(String.valueOf(this.tablaEscu.getValueAt(row,1)));
        Integer presu = parseInt(String.valueOf(this.tablaEscu.getValueAt(row,2)));
        Integer puntos = parseInt(String.valueOf(this.tablaEscu.getValueAt(row,3)));
        String pais = String.valueOf(this.tablaEscu.getValueAt(row,4));
        
        Escuderia escuAux = new Escuderia(nombre, anio, presu, puntos, pais);
        borrar = new BorrarEscuderia(this, true,escuAux);
        this.setVisible(false);
        borrar.setVisible(true);
    }//GEN-LAST:event_bajaBActionPerformed
   
    private void modificarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarBActionPerformed
        ModificarEscuderia modificar = null;
        int row = this.tablaEscu.getSelectedRow();
        String nombre = String.valueOf(this.tablaEscu.getValueAt(row,0));
        Integer anio = parseInt(String.valueOf(this.tablaEscu.getValueAt(row,1)));
        Integer presu = parseInt(String.valueOf(this.tablaEscu.getValueAt(row,2)));
        Integer puntos = parseInt(String.valueOf(this.tablaEscu.getValueAt(row,3)));
        String pais = String.valueOf(this.tablaEscu.getValueAt(row,4));
        
        Escuderia escuAux = new Escuderia(nombre, anio, presu, puntos, pais);
        modificar = new ModificarEscuderia(escuAux);
        this.setVisible(false);
        modificar.setVisible(true);
        
    }//GEN-LAST:event_modificarBActionPerformed

    private void seleccionarItem(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_seleccionarItem
        this.bajaB.setEnabled(true);
        this.modificarB.setEnabled(true);
    }//GEN-LAST:event_seleccionarItem

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListaEscuForm().setVisible(true);
            }
        });  
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton altaB;
    private javax.swing.JButton bajaB;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.awt.Label labelEscu;
    private javax.swing.JButton modificarB;
    private javax.swing.JTable tablaEscu;
    // End of variables declaration//GEN-END:variables
}
